package com.hmall.api.config;

import com.hmall.api.client.fallback.ItemClientFallbackFactory;
import com.hmall.api.client.fallback.UserClientFallbackFactory;
import com.hmall.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * OpenFeign远程调用配置类
 */
public class DefaultFeignConfig { //这里不加@Configuration注解

    /**
     * 配置openFeign日志级别
     * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }

    /**
     * 配置RequestInterceptor请求拦截器
     * 会拦截openfeign发出的所有请求，做进一步请求。
     * 这里添加了个请求头，把用户ID放进去传递给下游微服务。
     * @return
     */
    // 比较简单就在这里写了，拦截所有发出的Feign请求
    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {

                Long userId = UserContext.getUser();
                if (userId != null){
                    template.header("user-info",userId.toString());
                }

            }
        };
    }

    /**
     * item-service服务降级工厂类
     * @return
     */
    @Bean
    public ItemClientFallbackFactory itemClientFallbackFactory(){
        return new ItemClientFallbackFactory();
    }

    /**
     * user-service服务降级工厂类
     * @return
     */
    @Bean
    public UserClientFallbackFactory userClientFallbackFactory(){
        return new UserClientFallbackFactory();
    }
}
